package com.zhousc.springcloud;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import lombok.Cleanup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Controller {

    @Autowired
    private MyService myService;

    @Autowired
    private RequestCacheService requestCacheService;

    @GetMapping("fallback")
    public String fallback(){
        return myService.error();
    }

    @GetMapping("timeout")
    @HystrixCommand(
            fallbackMethod = "timeout2",
            commandProperties = {
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
            }
    )
    public String timeout(Integer timeout){
        return myService.retry(timeout);
    }

    public String timeout2(Integer timeout){
        return "success";
    }



    @GetMapping("requestCache")
    public Friend requestCache(String name){
        // 声明hytrix上线文，表明hytrix的缓存在一个上下文中有效，可以根据使用场景扩展到Session或服务器级别
        // 真实项目中可以用拦截器处理，表明同一个request有效
        // @Cleanup lombok关闭上线文，也可以使用try-finally
       @Cleanup HystrixRequestContext context = HystrixRequestContext.initializeContext();
        // 模拟调用两次服务
        Friend friend = requestCacheService.requestCache(name);
        friend = requestCacheService.requestCache(name);
        return friend;
    }
}
